package com.song.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.song.eduservice.entity.EduSubject;
import com.song.eduservice.entity.excel.SubjectData;
import com.song.eduservice.entity.subject.OneSubject;
import com.song.eduservice.entity.subject.TwoSubject;
import com.song.eduservice.listener.SubjectExcelListener;
import com.song.eduservice.mapper.EduSubjectMapper;
import com.song.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author song
 * @since 2020-03-29
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Autowired
    private EduSubjectMapper eduSubjectMapper;

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> findAllSubject() {
        QueryWrapper<EduSubject> qw = new QueryWrapper<>();
        qw.eq("parent_id", 0);
        //一级分类
        List<EduSubject> oneSubject = eduSubjectMapper.selectList(qw);

        QueryWrapper<EduSubject> qw2 = new QueryWrapper<>();
        qw.ne("parent_id", 0);
        //二级分类
        List<EduSubject> twoSubject = eduSubjectMapper.selectList(qw2);

        //集合封装
        List<OneSubject> list = new ArrayList<>();
        //遍历一级菜单
        for (EduSubject oSubject : oneSubject) {
            //把一级菜单放到OneSubject
            OneSubject one = new OneSubject();

            //one.setId(eduSubject.getId());
            //one.setTitle(eduSubject.getTitle());
            //将遍历出来的oSubject复制到tone
            BeanUtils.copyProperties(oSubject,one);
            //添加到list
            list.add(one);
            //遍历二级菜单
            List<TwoSubject> towList = new ArrayList<>();

            for (EduSubject tSubject : twoSubject) {
                //如果parentId==id说明有子级关系
                if(tSubject.getParentId().equals(oSubject.getId())){
                    TwoSubject two = new TwoSubject();
                    //将遍历出来的tSubject复制到two
                    BeanUtils.copyProperties(tSubject,two);
                    towList.add(two);
                }
            }
           one.setChildren(towList);
        }

        return list;
    }
}
